package com.fin.zw.aiqas.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;

public class FormulaUtil {


    public static void main(String[] args) throws Exception {
//        String mgs = " 0 | 0 & 1";
//        Integer result = jsonToBoolean(mgs);
//        System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
//        test();
        String json = "(aaaa |aabn )&(jsekw |uwheif)";
        System.out.println(splitJson(json));
//        Map<String, Integer> map = new HashMap<>();
//        map.put("aaaa", 0);
//        map.put("aabn", 1);
//        map.put("jsekw", 0);
//        map.put("uwheif", 1);
//        System.out.println("计算结果是：" + jsonToFormula(json, map));
    }

    private final static Logger log = LoggerFactory.getLogger(FormulaUtil.class);


    /**
     * 字符串转换对应逻辑运算，并结算对应的结果
     *
     * @param mgs
     * @return
     * @throws Exception
     */
    public static Integer jsonToBoolean(String mgs)  {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        Integer result = null;
        try {
            result = (Integer) engine.eval(mgs);
        } catch (ScriptException e) {
            log.error("没表达式+["+mgs+"]执行异常!!!!");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 数据转换
     *
     * @param json
     * @param map
     * @return
     * @throws Exception
     */
    public static Integer jsonToFormula(String json, Map<String, Integer> map) {
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            json = json.replace(entry.getKey(), entry.getValue().toString());
        }
        log.info("替换后的结果字符串:" + json);
        return jsonToBoolean(json);
    }

    /**
     * 将逻辑表达式进行分割成集合
     *
     * @param json
     * @return
     */
    public static List<String> splitJson(String json) {
        List<String> result = new ArrayList<>();
        //现在以 |，&,（,）进行分割
        String[] mgs = json.split("\\||&|\\(|\\)");
        List<String> resultList = new ArrayList<>(Arrays.asList(mgs));
        resultList.removeAll(Collections.singleton(""));
        for (String str : resultList) {
            result.add(str.trim());
        }
        return result;
    }
}
